<template>
  <ContentWrap :bodyStyle="{ padding: '10px 20px 0' }">
    <div class="processInstance-wrap-main">
      <el-scrollbar>
        <div class="text-#878c93 h-20px">流程：{{ processDefinition.name }}</div>
        <el-divider class="!my-8px" />

        <!-- 中间主要内容 tab 栏 -->
        <el-tabs v-model="activeTab">
          <!-- 表单信息 -->
          <el-tab-pane label="表单填写" name="form">
            <div class="form-scroll-area" v-loading="processInstanceStartLoading">
              <el-scrollbar>
                <el-row>
                  <el-col :span="15">
                    <form-create
                      :rule="startForm.rule"
                      v-model:api="fApi"
                      v-model="startForm.value"
                      :option="startForm.option"
                      @submit="submitForm"
                      @change="handleFormChange"
                    />
                  </el-col>

                  <el-col :span="6" :offset="3">
                    <!-- 流程时间线 -->
                    <ProcessInstanceTimeline
                      ref="timelineRef"
                      :activity-nodes="activityNodes"
                      :show-status-icon="false"
                      @select-user-confirm="selectUserConfirm"
                    />
                  </el-col>
                </el-row>
              </el-scrollbar>
            </div>
          </el-tab-pane>
          <!-- 流程图 -->
          <el-tab-pane label="流程图" name="diagram">
            <div class="form-scroll-area">
              <!-- BPMN 流程图预览 -->
              <ProcessInstanceBpmnViewer
                :bpmn-xml="bpmnXML"
                v-if="BpmModelTypeEnum.Bpmn === processDefinition.type"
              />
            </div>
          </el-tab-pane>
        </el-tabs>

        <!-- 底部操作栏 -->
        <div class="b-t-solid border-t-1px border-[var(--el-border-color)]">
          <!-- 操作栏按钮 -->
          <div
            v-if="activeTab === 'form'"
            class="h-50px bottom-10 text-14px flex items-center color-#32373c dark:color-#fff font-bold btn-container"
          >
            <el-button
              plain
              type="success"
              @click="submitForm"
              :disabled="processInstanceStartLoading"
            >
              <Icon icon="ep:select" />&nbsp; 发起
            </el-button>
            <el-button plain type="danger" @click="handleCancel">
              <Icon icon="ep:close" />&nbsp; 取消
            </el-button>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </ContentWrap>
</template>

<script setup lang="ts">
import { ProcessDefinitionApi, ProcessDefinitionInfoVO } from '@/api/bpm/process_definition'
import { ProcessInstanceApi, ApprovalNodeInfo, ApprovalDetail } from '@/api/bpm/process_instance'
import { setFormConfAndFields, parseFormFields } from '@/utils/formCreate'
import type { Api } from '@form-create/element-ui'
import ProcessInstanceBpmnViewer from '../detail/ProcessInstanceBpmnViewer.vue'
import ProcessInstanceTimeline from '../detail/ProcessInstanceTimeline.vue'
import { BpmModelTypeEnum } from '@/utils/constants'
import { debounce } from 'lodash-es'
import {
  CandidateStrategy,
  FieldPermissionType,
  NodeId
} from '@/components/bpmnProcessDesigner/src/consts'
import { useTagsView } from '@/hooks/web/useTagsView'

defineOptions({ name: 'BpmProcessStartForm' })

const props = defineProps<{
  processDefinition: ProcessDefinitionInfoVO
}>()
const emit = defineEmits(['cancel'])
const processInstanceStartLoading = ref(false) // 流程实例发起中
const route = useRoute() // 路由
const { push } = useRouter() // 路由
const tagsView = useTagsView()
const message = useMessage() // 消息弹窗

const fApi = ref<Api>()
const startForm: any = ref({
  rule: [],
  option: {},
  value: {}
}) // 流程表单详情
const startUserSelectTaskNodes = ref<ApprovalNodeInfo[]>([]) // 发起人需要选择审批人或抄送人的任务列表
const startUserSelectAssignees = ref({}) // 发起人选择审批人的数据
const tempStartUserSelectAssignees = ref({}) // 历史发起人选择审批人的数据，用于每次表单变更时，临时保存
const bpmnXML: any = ref(null) // BPMN 数据

const activeTab = ref('form') // 当前的 Tab
const activityNodes = ref<ApprovalNodeInfo[]>([]) // 审批节点信息

/** 设置表单信息、获取流程图数据 **/
const initProcessInfo = async (processDefinition: ProcessDefinitionInfoVO, formVariables?: any) => {
  startUserSelectTaskNodes.value = []
  startUserSelectAssignees.value = {}

  if (formVariables) {
    // 过滤一遍前端form实际需要的字段，后端返回的是流程实例全部的variables，包括审批中新增的
    const formFields = parseFormFields(processDefinition.formFields).map(
      (fieldObj) => fieldObj.field
    )
    for (const key in formVariables) {
      if (!formFields.includes(key)) {
        delete formVariables[key]
      }
    }
  }
  setFormConfAndFields(
    startForm,
    processDefinition.formConf,
    processDefinition.formFields,
    true,
    false,
    formVariables
  )

  await getApprovalDetail({
    processDefinitionId: processDefinition.id,
    processVariables: startForm.value.value ?? {}
  })

  // 加载流程图，流程定义列表中流程定义无流程图，需获取指定流程定义的详情
  const processDefinitionDetail: ProcessDefinitionInfoVO =
    await ProcessDefinitionApi.getProcessDefinition(processDefinition.id)
  if (processDefinitionDetail) {
    bpmnXML.value = processDefinitionDetail.bpmnXml
  }
}

const getApprovalDetail = async (obj: { processDefinitionId: string; processVariables: any }) => {
  const data: ApprovalDetail = await ProcessInstanceApi.getApprovalDetail({
    processDefinitionId: obj.processDefinitionId,
    activityId: NodeId.START_USER_NODE_ID, // 作为流程开始的活动id，对应simple类型的第一个用户启动任务(可以设置表单权限)
    processVariables: obj.processVariables
  })

  if (!data) {
    message.error('查询不到审批详情信息！')
    return
  }

  // 备份之前选择的节点审批人
  tempStartUserSelectAssignees.value = startUserSelectAssignees.value
  startUserSelectAssignees.value = {}

  // 获取审批节点信息，用于展示审批时间线 Timeline
  activityNodes.value = data.activityNodes

  // 获取发起人自选的任务节点列表
  startUserSelectTaskNodes.value = data.activityNodes?.filter(
    (node: ApprovalNodeInfo) => CandidateStrategy.START_USER_SELECT === node.candidateStrategy
  )

  // 恢复发起人自选的活动节点之前选择的候选人值
  if (startUserSelectTaskNodes.value?.length) {
    for (const node of startUserSelectTaskNodes.value) {
      if (tempStartUserSelectAssignees.value[node.id]?.length) {
        startUserSelectAssignees.value[node.id] = tempStartUserSelectAssignees.value[node.id]
      } else {
        startUserSelectAssignees.value[node.id] = []
      }
    }
  }

  // 获取表单字段权限
  const formFieldsPermission = data.formFieldsPermission
  if (formFieldsPermission) {
    Object.keys(formFieldsPermission).forEach((field) => {
      setFieldPermission(field, formFieldsPermission[field])
    })
  }
}

/** 获取审批详情 */
const debounceGetApprovalDetail = debounce(getApprovalDetail, 1000)

const handleFormChange = (_field, _value, rule, _api, _setFlag) => {
  if (rule.type === 'input') {
    // 文本类的表单字段，一般是不会作为流程中的路径或候选人计算依据的，即使真有也仅仅是影响推导的准确性，但放开太浪费服务端资源，没必要
    return
  }
  // todo 需要继续优化，非影响流程推导的字段变更不重复推导
  debounceGetApprovalDetail({
    processDefinitionId: props.processDefinition.id,
    processVariables: startForm.value.value ?? {}
  })
}

/**
 * 设置表单权限
 */
const setFieldPermission = (field: string, permission: string) => {
  if (permission === FieldPermissionType.READ) {
    //@ts-ignore
    fApi.value?.disabled(true, field)
  }
  if (permission === FieldPermissionType.WRITE) {
    //@ts-ignore
    fApi.value?.disabled(false, field)
  }
  if (permission === FieldPermissionType.NONE) {
    //@ts-ignore
    fApi.value?.hidden(true, field)
  }
}

const submitForm = async () => {
  if (!fApi.value || !props.processDefinition) {
    return
  }
  await fApi.value.validate()
  // 如果有发起人指定审核人节点，需要做校验
  if (startUserSelectTaskNodes.value?.length) {
    for (const taskNode of startUserSelectTaskNodes.value) {
      if (!startUserSelectAssignees.value[taskNode.id]?.length) {
        return message.warning(`请选择${taskNode.name}的候选人`)
      }
    }
  }

  console.log(
    'submitForm:',
    props.processDefinition.id,
    startForm.value.value ?? {},
    startUserSelectAssignees.value
  )

  processInstanceStartLoading.value = true
  try {
    await ProcessInstanceApi.createProcessInstance({
      processDefinitionId: props.processDefinition.id,
      variables: startForm.value.value,
      startUserSelectAssignees: startUserSelectAssignees.value
    })
    message.success('发起流程成功')
    if (route.query.processInstanceId) {
      // 重复发起的情形
      tagsView.closeCurrent()
    } else {
      // 普通发起的情形，关闭发起窗口即可，保留发起流程tag
      handleCancel()
    }
    await push({ name: 'BpmProcessInstanceMy', state: { reload: true } })
  } finally {
    processInstanceStartLoading.value = false
  }
}

const handleCancel = () => {
  emit('cancel')
}

const selectUserConfirm = (id: string, userList: any[]) => {
  startUserSelectAssignees.value[id] = userList?.map((item: any) => item.staffId)
}

defineExpose({ initProcessInfo })
</script>

<style scoped lang="scss">
$wrap-padding-height: 20px;
$wrap-margin-height: 15px;
$button-height: 51px;
$process-header-height: 105px;

.processInstance-wrap-main {
  height: calc(
    100vh - var(--top-tool-height) - var(--tags-view-height) - var(--app-content-padding) - var(
        --app-footer-height
      ) -
      18px
  );
  max-height: calc(
    100vh - var(--top-tool-height) - var(--tags-view-height) - var(--app-content-padding) - var(
        --app-footer-height
      ) -
      18px
  );
  overflow: auto;

  .form-scroll-area {
    height: calc(
      100vh - var(--top-tool-height) - var(--tags-view-height) - var(--app-content-padding) - var(
          --app-footer-height
        ) -
        18px - $process-header-height - 40px
    );
    max-height: calc(
      100vh - var(--top-tool-height) - var(--tags-view-height) - var(--app-content-padding) - var(
          --app-footer-height
        ) -
        18px - $process-header-height - 40px
    );
    overflow: auto;
  }
}

.form-box {
  :deep(.el-card) {
    border: none;
  }
}
</style>
